using System;
using System.Text;


namespace ThalesHsmComms
{
	sealed public class HexConverter
	{
		private readonly static char[] hexTable = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

		public HexConverter()
		{
		}

	    public static String FromBinary2HexString(byte[] binaryData) 
		{
			return FromBinary2HexString(binaryData,binaryData.Length);
	    }


		public static String FromBinary2HexString(byte[] binaryData, int len) 
		{
			byte lo, hi;
	
			// get the length of the array
			StringBuilder str  = new StringBuilder(len * 2);
	
			int creepy;
			for (int i = 0; i < len; i++) 
			{
				creepy = (int) (binaryData[i]);
				lo = (byte) (creepy & 0x0F);
				hi = (byte) ((creepy >> 4) & 0x0F);
	
				str.Append(hexTable[hi]);
				str.Append(hexTable[lo]);
			}
	
			return str.ToString();
		}

		public static byte[] FromHex2Binary(string hexData)
		{
			byte b1 = 0;
			byte b2 = 0;
			int len = hexData.Length;
			byte[] data = new byte[len / 2];
			int idx = 0;
			
			for(int i = 0; i < len; i+=2)
			{
				b1 = (byte) (hexData[i] - '0');
				if(b1 > 9)
					b1 -= 7;

				b2 = (byte) (hexData[i+1] - '0');
				if(b2 > 9)
					b2 -= 7;

				data[idx++] = (byte)((b1 << 4) + b2);
			}

			return data;
		}

	   	public static byte[] FromShort2HexBinary(short val) 
		{
	        byte[] str = new byte[2];
	        byte hi, lo;
	
	        // get hex for high byte of integer
	        hi = (byte) ((val >> 8) & 0x00FF);
	        lo = (byte) (val & 0x00FF);
	
	        str[0] = hi;
	        str[1] = lo;
	
	        return str;
	    }

	    public static String FromShort2HexString(short val) 
		{
	        StringBuilder str = new StringBuilder(4);
	        byte hi, lo;
	
	        // get hex for high byte of integer
	        hi = (byte) ((val >> 12) & 0x000F);
	        lo = (byte) ((val >> 8) & 0x000F);
	
	        str.Append(hexTable[hi]);
	        str.Append(hexTable[lo]);
	
	        // get hex for low byte of integer
	        hi = (byte) ((val >> 4) & 0x000F);
	        lo = (byte) (val & 0x000F);
	
			str.Append(hexTable[hi]);
			str.Append(hexTable[lo]); 
	
			string ret = str.ToString();

			return ret;
	    }
	}
}

